package com.aaa.utils;

import com.aaa.service.MouseServiceImpl;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author yudejie2020
 */
public class MyDynamicProxyCGlib {

    public Object getProxyObj(Class<?> clazz){
        //1,创建字节码增强器
        Enhancer enhancer=new Enhancer();

        //2，指定需要增强的类
        enhancer.setSuperclass(clazz);
        //3,设置回调函数
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy Proxy) throws Throwable {
                //增强处理
                System.out.println("日志："+method.getName()+"执行了"+new Date());
                //执行目标对象的方法
                Object invokeSuper=Proxy.invokeSuper(o,objects);
                return invokeSuper;
            }
        });
        //4，返回代理对象
        return enhancer.create();
//        return null;
    }

    public static void main(String[] args) {
        MyDynamicProxyCGlib myDynamicProxyCGlib=new MyDynamicProxyCGlib();
        MouseServiceImpl proxyObj=(MouseServiceImpl) myDynamicProxyCGlib.getProxyObj(MouseServiceImpl.class);
        proxyObj.buyMouse(400);
    }
}
